package com.zjuh.goodboy.filter.filters;

import java.util.List;

import com.zjuh.goodboy.awires.AppContextAwire;
import com.zjuh.goodboy.claw.ParseTemplate;
import com.zjuh.goodboy.claw.link.Link;
import com.zjuh.goodboy.context.AppContext;
import com.zjuh.goodboy.filter.FilterContext;
import com.zjuh.goodboy.items.Item;
import com.zjuh.goodboy.parsers.ExprParseTemplate;
import com.zjuh.goodboy.parsers.ItemExpr;
import com.zjuh.goodboy.store.item.ItemStore;

public class ItemParseFilter extends BaseFilter implements AppContextAwire {

	private AppContext appContext;
	
	@Override
	public void onFilter(Link link, String input, FilterContext filterContext) {
		ItemExpr itemExpr = (ItemExpr)filterContext.getAttribute("itemExpr");
		ParseTemplate parseTemplate = new ExprParseTemplate(itemExpr, appContext);
		List<Item> items = parseTemplate.parse(link, input);
		try {
			((ItemStore)appContext.getObject("itemStore")).saveItems(items);
		} catch (Exception e) {
			log.error("onFilter failed", e);
		}
	}

	@Override
	public void setAppContext(AppContext appContext) {
		this.appContext = appContext;
	}

}
